package com.cola.colaboot.module.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cola.colaboot.config.security.SecurityUtils;
import com.cola.colaboot.module.system.mapper.SysAccessMapper;
import com.cola.colaboot.module.system.mapper.SysRoleAccessMapper;
import com.cola.colaboot.module.system.pojo.SysAccess;
import com.cola.colaboot.module.system.pojo.SysRoleAccess;
import com.cola.colaboot.module.system.service.SysAccessService;
import com.cola.colaboot.utils.MenuUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SysAccessServiceImpl extends ServiceImpl<SysAccessMapper, SysAccess> implements SysAccessService {
    @Autowired
    private SysRoleAccessMapper roleAccessMapper;

    @Override
    public List<SysAccess> getAccessByUserName(String username) {
        return baseMapper.getAccessByUserName(username);
    }

    @Override
    public List<SysAccess> listRoleAccessByParent(SysAccess access) {
        Integer roleId = SecurityUtils.currentUser().getRoleId();
        return baseMapper.listRoleAccessByParent(access,roleId);
    }

    @Override
    public List<SysAccess> getChildren(String parentId) {
        Integer roleId = SecurityUtils.currentUser().getRoleId();
        return baseMapper.getChildren(parentId,roleId);
    }

    @Override
    public void doSave(SysAccess access) {
        setMenuLevel(access);//设置菜单级别
        if (access.getId() == null){
            save(access);
            Integer roleId = SecurityUtils.currentUser().getRoleId();//角色授权
            SysRoleAccess roleAccess = new SysRoleAccess(roleId,access.getId());
            roleAccessMapper.insert(roleAccess);
        }else {
            updateById(access);
        }
    }

    /**
     *  设置菜单级别
     */
    private void setMenuLevel(SysAccess access) {
        if (access.getMenuLevel() == 1 && access.getParentId() != null){//选择了菜单并且选择了父级
            SysAccess parentAccess = getById(access.getParentId());
            access.setMenuLevel(parentAccess.getMenuLevel() + 1);
        }
    }

    @Override
    public void deleteNative(String id) {//删除子集还未做
        roleAccessMapper.delByAccessId(id);
        removeById(id);
    }

    @Override
    public List<SysAccess> treeRoleAccess(Integer menuType) {
        Integer roleId = SecurityUtils.currentUser().getRoleId();
        List<SysAccess> sysAccesses = baseMapper.treeRoleAccess(roleId,menuType);
        return MenuUtil.setTree(sysAccesses);
    }

    @Override
    public List<Integer> getAccessIdsByRole(Integer roleId) {
        return baseMapper.getAccessIdsByRole(roleId);
    }
}
